﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;

namespace Recive
{
    public partial class Form1 : Form
    {
        public delegate void Complete();
        public event Complete finish;
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //为了不使主窗口线程阻塞
            //在窗体的加载事件中,创建一个线程,专门用来接收图片
            Control.CheckForIllegalCrossThreadCalls = true;
            Thread th = new Thread(new ThreadStart(RC));
            th.Start();           
        }

        public void RC()
        {
            /************************************************************************/
            /* 接收方为服务器端,监听,等待客户端发送图片,并作显示                    */
            /************************************************************************/
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            EndPoint point = new IPEndPoint(IPAddress.Any, 10000);
            sock.Bind(point);
            sock.Listen(10);         
          
            while (true)
            {
                Socket client = sock.Accept();              
                byte[] bitLen=new byte[8];
                client.Receive(bitLen,bitLen.Length,SocketFlags.None);
                //第一步接收文件的大小
                long contentLen = BitConverter.ToInt64(bitLen,0);
                int size = 0;
                MemoryStream ms = new MemoryStream();
                //循环接收文件的内容,如果接收完毕,则break;
                while (size<contentLen)
                {
                    //分多次接收,每次接收256个字节,
                    byte[] bits = new byte[256];
                    int r = client.Receive(bits, bits.Length, SocketFlags.None);
                    if (r <= 0) break;
                    ms.Write(bits,0,r);                  
                    size += r;
                }
                client.Close();
                //接收到就显示,然后关闭当前连接,继续监听
                wangle(ms);
            }
           
        }
        public void wangle(MemoryStream ms)
        {
            Image img = Image.FromStream(ms);
            picBox.Image = null;
            picBox.Image = img;
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        private void picBox_Click(object sender, EventArgs e)
        {

        }

        private void picBox_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            MessageBox.Show("");
        }
    }
}
